package com.zyk.leetcode;

import java.util.*;

/**
 * @author zhangsan
 * @date 2021/5/2 12:26
 */
public class C49 {

    // 字符排序, map统计. 时间复杂度O(N* K*logK )  n个字符,每个字符排序K*logK.
    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            if(!map.containsKey(key)) map.put(key, new ArrayList<>());
            map.get(key).add(str);
        }
        return new ArrayList<>(map.values());
    }

    // 计数排序
    public static List<List<String>> groupAnagrams2(String[] strs) {
        int[] cnt = new int[26];
        Map<String, List<String>> map = new HashMap<>();
        for (String s : strs) {
            Arrays.fill(cnt, 0);
            char[] str = s.toCharArray();
            for (char c : str) {
                cnt[c-'a']++;
            }
            StringBuilder key = new StringBuilder();
            for (int i = 0; i < 26; i++) {
                key.append(cnt[i]);
            }
            String k = key.toString();
            if(!map.containsKey(k)) map.put(k, new ArrayList<>());
            map.get(k).add(s);
        }
        return new ArrayList<>(map.values());
    }


    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        System.out.println(groupAnagrams(strs));
        System.out.println(groupAnagrams2(strs));
    }

}
